package com.sixseven.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixseven.bean.Cowry;
import com.sixseven.service.CowryService;
import com.sixseven.utils.FileNameUtils;
import com.sixseven.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author Belly
 * @version 1.1.0
 */
@RestController
@Slf4j
public class CowryController {
    @Value("${pictureFile.path}")
    private String absolutePath;
    @Resource
    private CowryService cowryService;
    @RequestMapping ("/cowryList")
    public Result cowryList(@RequestParam Integer status){
//        log.info("status={}", status);
        if (status == null){
            return Result.error();
        }
        List<Cowry> cowryList = cowryService.queryCowryListByStatus(status);
        if (cowryList == null){
            return Result.error();
        }
        return Result.success(cowryList);
    }
    @RequestMapping("/listPageByConditionName")
    public Result listPageByConditionName(@RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "5") Integer pageSize,
                                          @RequestParam(defaultValue = "") String searchName){
//        log.info("pageNum={}", pageNum);
//        log.info("pageSize={}", pageSize);
//        log.info("searchName={}", searchName);
        LambdaQueryWrapper<Cowry> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.like(Cowry::getName, searchName);
        Page<Cowry> cowryPageList =
                cowryService.page(
                        new Page<>(pageNum, pageSize), objectLambdaQueryWrapper);
        return Result.success(cowryPageList);
    }
    @PostMapping("/addCowry")
    public Result addCowry(@Validated @RequestBody Cowry cowry, Errors errors){
        if (errors.hasErrors()){
            return Result.error();
        }
        if (cowry == null){
            return Result.error();
        }
        boolean save = cowryService.save(cowry);
//        log.info("save={}", save);
        if (!save){
            return Result.error();
        }
        return Result.success("200", "添加成功");
    }
    @PostMapping("/upload")
    public Result upload(@RequestPart("img") MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        if (multipartFile == null){
            return Result.error();
        }
        if (!multipartFile.isEmpty()){
            String filePath = FileNameUtils.FURN_IMG_PATH + FileNameUtils.getYearMothDay();
            File filePathDirectory = new File(absolutePath + filePath);
            if (!filePathDirectory.exists()){
                filePathDirectory.mkdirs();
            }
//            log.info("imagePath={}", filePathDirectory);
            originalFilename = UUID.randomUUID() + "_"
                    + System.currentTimeMillis() + "_" + originalFilename;
            multipartFile.transferTo(new File(filePathDirectory + "/" + originalFilename));
            return Result.success(filePath + "/" + originalFilename);
        }
        return Result.error();
    }
    @DeleteMapping("/deleteCowry/{id}")
    public Result deleteCowry(@PathVariable Integer id){
//        log.info("id={}", id);
        if (id == null){
            return Result.error();
        }
        //得到旧照片路径
        String imgPath = cowryService.getById(id).getImgPath();
        if (!imgPath.isEmpty()){
            File filePathDirectory = new File(absolutePath + imgPath);
            if (filePathDirectory.exists()){
                filePathDirectory.delete();//删除旧照片
            }
        }
        boolean remove = cowryService.removeById(id);
        if (!remove){
            return Result.error();
        }
        return Result.success("200", "删除成功");
    }
    @PutMapping("/modifyCowry")
    public Result modifyCowry(@RequestBody Cowry cowry){
        if (cowry == null){
            return Result.error();
        }
        //得到旧照片路径
        String imgPath = cowryService.getById(cowry.getId()).getImgPath();
        if (!imgPath.isEmpty()){
            File filePathDirectory = new File(absolutePath + imgPath);
            if (filePathDirectory.exists()){
                filePathDirectory.delete();//删除旧照片
            }
        }
        boolean update = cowryService.updateById(cowry);
        if (!update){
            return Result.error();
        }
        return Result.success("200", "修改成功");
    }
    @GetMapping("/deleteLastImg")
    public Result deleteLastImg(@RequestParam String lastImageUrl){
//        log.info("lastImageUrl={}", lastImageUrl);
        if (!lastImageUrl.isEmpty()){
            File filePathDirectory = new File(absolutePath + lastImageUrl);
            if (filePathDirectory.exists()){
                filePathDirectory.delete();//删除旧照片
            }
            return Result.success(null);
        }
        return Result.error();
    }

    @GetMapping("/searchByName")
    public Result searchByName(@RequestParam String keyword){
//        log.info("keyword={}", keyword);
        List<com.sixseven.document.Cowry> cowries = cowryService.highLightSearch(keyword);
        if (cowries.size() == 0){
            return Result.error();
        }
        return Result.success(cowries);
    }
}
